<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>供应商</h3>
      <el-button size="small" type="success" @click="handleAdd">
        <i class="el-icon-plus" />
        新增
      </el-button>
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wapper">
        <div>
          <el-form ref="form" :model="form" :inline="true" label-width="80px">
            <el-form-item label="">
              <el-select
                v-model="listQuery.supplierTypeId"
                clearable
                size="small"
                placeholder="请选择供应商类型"
                style="width: 200px"
                @change="handleSupplierTypeChange"
              >
                <el-option
                  v-for="item in supplierTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input
                v-model="listQuery.keyword"
                size="small"
                style="width: 300px"
                placeholder="请输入供应商名字"
                clearable
              />
            </el-form-item>
            <!-- <el-form-item label="">
              <el-checkbox v-model="listQuery.includeSalesperson"
                >包含销售人员查询</el-checkbox
              >
            </el-form-item>
            <el-form-item label="">
              <el-checkbox
                v-model="listQuery.showDisabled"
                style="margin-left: 15px"
                >显示等用客户</el-checkbox
              >
            </el-form-item> -->
            <el-form-item label="">
              <el-button
                type="primary"
                size="small"
                style="margin-left: 15px"
                @click="handleFilter"
              >查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>

    <!-- 操作按钮区域 -->

    <!-- <el-card> -->
    <div class="table-operations">
      <el-form ref="form" :model="form" :inline="true" label-width="80px">
        <el-form-item label="">
          <el-select
            v-model="listQuery.supplierTypeId"
            clearable
            size="small"
            placeholder="请选择供应商类型"
            style="width: 200px"
            @change="handleSupplierTypeChange"
          >
            <el-option
              v-for="item in supplierTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            size="small"
            style="width: 300px"
            placeholder="请输入供应商名字"
            clearable
          />
        </el-form-item>
        <!-- <el-form-item label="">
              <el-checkbox v-model="listQuery.includeSalesperson"
                >包含销售人员查询</el-checkbox
              >
            </el-form-item>
            <el-form-item label="">
              <el-checkbox
                v-model="listQuery.showDisabled"
                style="margin-left: 15px"
                >显示等用客户</el-checkbox
              >
            </el-form-item> -->
        <el-form-item label="">
          <el-button
            type="primary"
            size="small"
            style="margin-left: 15px"
            @click="handleFilter"
          >查询</el-button>
        </el-form-item>

      </el-form>
      <!-- <el-button
          type="primary"
          size="small"
          class="filter-trigger"
          @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
          <i
            :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
          ></i>
        </el-button> -->
      <!-- <el-button
          type="success"
          @click="handleAdd"
          size="small"
          icon="el-icon-plus"
          >新增</el-button
        > -->
      <!-- <el-button type="warning" @click="handleBatchEdit" size="small"
          >批量修改</el-button
        > -->
      <!-- <el-button type="danger" @click="handleDisable" size="small"
          >禁用</el-button
        >
        <el-button type="success" @click="handleEnable" size="small"
          >启用</el-button
        >
        <el-button type="primary" @click="handleImport" size="small"
          >导入</el-button
        >
        <el-button type="primary" @click="handleExport" size="small"
          >导出</el-button
        > -->
      <!-- <el-button @click="handleDelete" size="small">删除</el-button> -->
    </div>
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="supplierList"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      header-cell-style="background-color: #f5f7fa; color: #333;"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->

      <el-table-c label="供应商类别" prop="customerType" align="center" />
      <el-table-column label="供应商编号" prop="no" align="center" />
      <el-table-column label="供应商名称" prop="name" align="center" />
      <el-table-column
        label="供应商类型"
        prop="supplierTypeName"
        align="center"
      />
      <el-table-column align="center" prop="contacts" label="联系人" />
      <el-table-column align="center" prop="mobile" label="手机号" />
      <el-table-column align="center" prop="status" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="(val) => handleStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="createTime"
        label="创建时间"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="自定义字段1" prop="customize_1" align="center" /> -->
      <!-- <el-table-column label="自定义字段2" prop="customize_2" align="center" /> -->
      <!-- <el-table-column label="业务员" prop="employeeName" align="center" /> -->
      <!-- <el-table-column label="首要联系人" prop="contacter" align="center" />
        <el-table-column label="增值税率%" prop="taxRate" align="center" />
        <el-table-column
          label="银行账号"
          prop="cardNo"
          align="center"
          width="180"
        />
        <el-table-column label="开户银行" prop="bank" align="center" />
        <el-table-column
          label="纳税人识别号"
          prop="taxPayerNo"
          align="center"
        />
        <el-table-column label="手机" prop="mobile" align="center" />
        <el-table-column label="座机" prop="telephone" align="center" />
        <el-table-column
          label="QQ/微信/Email"
          prop="socialContact"
          align="center"
        />
        <el-table-column
          label="联系地址"
          prop="address"
          align="center"
          width="180"
        /> -->
      <!-- <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column label="应付款余额" prop="difMoney" align="center" /> -->
      <!-- <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column> -->
      <!-- <el-table-column label="是否物流公司" align="center">
          <template slot-scope="scope">
            {{ scope.row.isLogisticsCompany ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="是否关联系统物流" align="center">
          <template slot-scope="scope">
            {{ scope.row.isSystemLogistics ? "是" : "否" }}
          </template>
        </el-table-column> -->

      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            <!-- <i class="el-icon-edit"></i> -->
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            <!-- <i class="el-icon-delete"></i> -->
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <!-- </el-card> -->

    <!-- 添加供应商弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form
        ref="supplierForm"
        :model="supplierForm"
        :rules="rules"
        label-width="120px"
        size="small"
      >
        <!-- 基础信息 -->
        <el-form-item label="供应商编号" prop="no">
          <el-input v-model="supplierForm.no" placeholder="请输入供应商编号" />
        </el-form-item>

        <el-form-item label="供应商名称" prop="name">
          <el-input
            v-model="supplierForm.name"
            placeholder="请输入供应商名称"
          />
        </el-form-item>

        <el-form-item label="联系人" prop="contacts">
          <el-input
            v-model="supplierForm.contacts"
            placeholder="请输入联系人"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="supplierForm.mobile" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="供应商类型" prop="supplierTypeId">
          <el-select
            v-model="supplierForm.supplierTypeId"
            clearable
            placeholder="请选择供应商类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in supplierTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="自定义字段1" prop="customize_1">
          <el-input
            v-model="supplierForm.customize_1"
            placeholder="请输入自定义字段1"
          />
        </el-form-item>

        <el-form-item label="自定义字段2" prop="customize_2">
          <el-input
            v-model="supplierForm.customize_2"
            placeholder="请输入自定义字段2"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selSupplierListApi,
  addSupplierApi,
  updateSupplierApi,
  deleteSupplierApi,
  selSupplierTypeListApi,
  updateSupplierStatusByIdApi
} from '@/api/system'

export default {
  name: 'Supplier',
  data() {
    // 手机号验证规则
    const validateMobile = (rule, value, callback) => {
      const mobileRegex = /^1[3-9]\d{9}$/
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!mobileRegex.test(value)) {
        callback(new Error('请输入正确的手机号格式'))
      } else {
        callback()
      }
    }

    return {
      list: [],
      total: 0,
      listLoading: false,
      // 供应商列表查询参数
      listQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        supplierTypeId: '' // 供应商类型
      },
      // 供应商类别查询
      supplierTypeQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        status: ''
      },
      customerTypeOptions: [
        { value: 0, label: '全部' },
        { value: 1, label: '华中地区' },
        { value: 2, label: '华北地区' },
        { value: 3, label: '华南地区' },
        { value: 4, label: '广东省内' },
        { value: 5, label: '批发' },
        { value: 6, label: '零售' }
      ],
      multipleSelection: [],
      // 是否显示搜索区域
      isFilterVisible: false,
      dialogVisible: false,
      supplierForm: {
        id: null,
        contacts: '', // 联系人
        customize_1: '', // 自定义字段1
        customize_2: '', // 自定义字段2
        mobile: '', // 手机号
        name: '', // 名称
        no: '', // 编号
        supplierTypeId: '' // 供应商类型ID，确保是数字类型
      },
      supplierTypeList: [], // 供应商类型列表
      rules: {
        contacts: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        no: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        supplierTypeId: [
          { required: true, message: '请选择供应商类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.supplierForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getSupplierList()
    this.getSupplierTypeList()
  },
  methods: {
    // 获取供应商列表
    async getSupplierList() {
      this.listLoading = true
      try {
        const res = await selSupplierListApi(this.listQuery)
        this.supplierList = res.records || []
        this.total = res.total || 0
      } catch (error) {
        console.error('获取供应商列表失败:', error)
        this.supplierList = []
        this.total = 0
        this.$message.error('获取供应商列表失败')
      } finally {
        this.listLoading = false
      }
    },
    // 获取供应商类型列表
    async getSupplierTypeList() {
      const res = await selSupplierTypeListApi(this.supplierTypeQuery)
      this.supplierTypeList = res.records || []
    },
    // 供应商类型改变
    handleSupplierTypeChange(val) {
      this.listQuery.page = 1
      this.getSupplierList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      // this.getList();
      this.getSupplierList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      // this.getList();
      this.getSupplierList()
    },
    handleFilter() {
      this.listQuery.page = 1
      // this.getList();
      this.getSupplierList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true
      this.supplierForm = {
        id: null,
        contacts: '',
        customize_1: '',
        customize_2: '',
        mobile: '',
        name: '',
        no: '',
        supplierTypeId: '' // 默认值设为数字 0
      }
    },
    handleEdit(row) {
      this.dialogVisible = true
      this.supplierForm = {
        id: row.id,
        contacts: row.contacts,
        customize_1: row.customize_1,
        customize_2: row.customize_2,
        mobile: row.mobile,
        name: row.name,
        no: row.no,
        supplierTypeId: Number(row.supplierTypeId) || 0 // 确保转换为数字类型
      }
    },
    submitForm() {
      this.$refs.supplierForm.validate(async(valid) => {
        if (valid) {
          try {
            const params = {
              contacts: this.supplierForm.contacts,
              customize_1: this.supplierForm.customize_1,
              customize_2: this.supplierForm.customize_2,
              mobile: this.supplierForm.mobile,
              name: this.supplierForm.name,
              no: this.supplierForm.no,
              supplierTypeId: Number(this.supplierForm.supplierTypeId) || 0 // 确保转换为数字类型
            }

            if (!this.supplierForm.id) {
              // 新增供应商
              const res = await addSupplierApi(params)
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            } else {
              // 编辑供应商
              const res = await updateSupplierApi({
                ...params,
                id: this.supplierForm.id
              })
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            }

            this.dialogVisible = false
            this.getSupplierList() // 刷新列表数据
          } catch (error) {
            console.error('操作失败:', error)
            this.$message({
              type: 'error',
              message: '操作失败: ' + (error.message || '未知错误')
            })
          }
        }
      })
    },
    handleView(row) {
      // 处理查看
      this.$message({
        message: '查看客户: ' + row.name,
        type: 'info'
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该供应商, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await deleteSupplierApi(row.id)
            if (res.code === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getSupplierList() // 刷新列表数据
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message({
              type: 'error',
              message: '删除失败: ' + (error.message || '未知错误')
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        })
    },
    handleBatchEdit() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要修改的客户',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '批量修改选中的客户',
        type: 'info'
      })
    },
    handleEnable() {
      // 处理启用
      this.$message({
        message: '启用客户',
        type: 'info'
      })
    },
    handleDisable() {
      // 处理禁用
      this.$message({
        message: '禁用客户',
        type: 'info'
      })
    },
    handleImport() {
      // 处理导入
      this.$message({
        message: '导入客户',
        type: 'info'
      })
    },
    handleExport() {
      // 处理导出
      this.$message({
        message: '导出客户',
        type: 'info'
      })
    },
    // 供应商状态改变
    async handleStatusChange(row, val) {
      try {
        const res = await updateSupplierStatusByIdApi({
          id: row.id,
          status: val
        })

        if (res.code === 1) {
          this.$message.success(val === 1 ? '供应商已启用' : '供应商已禁用')
          // 刷新列表数据
          this.getSupplierList()
        } else {
          this.$message.error(res.msg || '状态更新失败')
        }
      } catch (error) {
        // 发生错误时恢复原始状态
        row.status = val === 1 ? 2 : 1
        console.error('更新供应商状态失败:', error)
        this.$message.error('更新供应商状态失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.filter-container {
  padding-bottom: 15px;
  margin-bottom: 15px;
}
.button-container {
  margin-bottom: 15px;
}
.search-wapper {
  margin-bottom: 15px;
}
/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #EBEEF5;
  margin: 13px 0;
}
.table-operations {
  margin-bottom: 15px;
}
.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}
.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}
.dialog-footer {
  text-align: right;
}
</style>
